package com.daafan.minilib.activity;

import java.io.File;
import java.util.List;

import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.daafan.minilib.R;
import com.daafan.minilib.data.BookData;
import com.daafan.minilib.data.BookList;
import com.daafan.minilib.service.BookListService;
import com.daafan.minilib.util.AppUtils;
import com.umeng.update.UmengUpdateAgent;

public class SettingActivity extends BaseActivity implements OnClickListener {

	Button	btn_clear;
	Button	btn_version;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_setting);

		initTopBar("设置", R.drawable.back, 0);

		initView();
	}

	private void initView() {
		btn_clear = (Button) findViewById(R.id.btn_setting_clear);
		btn_clear.setOnClickListener(this);

		btn_version = (Button) findViewById(R.id.btn_setting_version);
		btn_version.setOnClickListener(this);
		btn_version.setText("版本检测 " + AppUtils.getVersionName());
	}

	@Override
	protected void onTopLeftClick() {
		back();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.btn_setting_clear:
				showConfirmDialog("清除缓存", "是否确认?", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						mImageLoader.getDiscCache().clear();
						// deleteBooks();

						// 将数据库所有books状态重置
						// BookList bookList = new BookList();
						// bookList.restore(mContext);
						//
						// for (BookData book : bookList.datas) {
						// book.countBit = 1;
						// book.current = 0;
						// book.isDownloading = false;
						// book.isFinish = false;
						//
						// book.update(mContext);
						// }

						// bookList.deleteAllList(mContext);
						// bookList.saveList(mContext);

						// 删除电子杂志
						new File(AppUtils.getMyCacheDir("apk") + "ejournal.apk").delete();

						SharedPreferences settings = getSharedPreferences(EJournalActivity.SHAREPREFERENCE, 0);
						Editor editor = settings.edit();
						editor.putInt(EJournalActivity.PROGRESS, 0);
						editor.putBoolean(EJournalActivity.DOWNLOADING, false);
						editor.putBoolean(EJournalActivity.FINISH, false);

						editor.commit();
					}
				});

				break;

			case R.id.btn_setting_version:

				UmengUpdateAgent.update(mContext);

				break;

			default:
				break;
		}
	}

	private void deleteBooks() {
		BookList tbookList = new BookList();
		tbookList.restore(getApplicationContext());
		List<BookData> bookList = tbookList.datas;

		for (BookData book : bookList) {
			try {
				new File(BookListService.getAPKName(book.bookid)).delete();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}
}
